package cn.yunhe.controller;

import cn.yunhe.entity.Result;
import cn.yunhe.entity.User;
import cn.yunhe.service.IUserService;
import com.github.pagehelper.Page;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
/**
 * RestController的作用，它会将此类中的所有的非基本数据类型（String）的方法的返回值都解析成json的格式
 * string就返回字符串 Integer 就返回整形
 * 如果仍想在此类中跳转页面，就要使用ModelAndView(“页面逻辑名称”)
 */
public class UserController {

    @Resource
    private IUserService userSevice;

    @RequestMapping("/list")
    public ModelAndView toList(){
        return new ModelAndView("list");

    }

    @RequestMapping("/getPage")
    public Map queryUserByPage(int pageNum, int pageSize, User user){

        Map<String ,Object> map=new HashMap<String ,Object>();
        map.put("pageSize",pageSize);
        map.put("pageNum",pageNum);
        map.put("user",user);

        Page page=userSevice.getLikeUsers(map);
        map.put("page",page);
        map.put("totalPages",page.getPages());
        return map;
    }

    @RequestMapping("/add")
    public Result  addUser(User user){
        userSevice.addUser(user);
        return new Result();
    }

    @RequestMapping("/editpage")
    public ModelAndView findUser(User user){
        User user1=userSevice.getUser(user);
        Map<String ,Object> maps=new HashMap<String, Object>();
        maps.put("data",user1);
        return new ModelAndView("edit",maps);
    }
    @RequestMapping("/edit")
    public Result editUser(User user){
        userSevice.editUser(user);
        return new Result();
    }



    @RequestMapping("/login")
    public ModelAndView toLogin(){
        return new ModelAndView("login");
    }

    @RequestMapping("/userLogin")
    public String  userLogin(User user, HttpSession session, Model model){

        Integer flag=userSevice.selectByNameAndPass(user);

        System.out.println(flag);
        if(flag!=null){
            session.setAttribute("user",user);
            return "redirect:/userList";
        }else{
            model.addAttribute("msg","登录失败");
            return "login";
        }
    }

    @RequestMapping("/userList")
    public String findAll(Model model){
        List<User > list=userSevice.selectAll();
        model.addAttribute("list",list);
        return "list";
    }
}
